<template>
  <el-card shadow="never">
    <div slot="header" class="clearfix">
      <span>聊天室</span>
      <el-button style="float: right; padding: 3px 0" type="text" @click="again">重新连接</el-button>
    </div>
    <div style="height: 320px;">
      <div class="container" ref="container">
        <div class="message" v-for="(item,index) in dataList" :key="index" :class="item.type">
          <img :src="item.avatar" alt="Avatar" class="message-avatar">
          <div style="max-width: 75%">
            <p class="message-info">{{ item.info }}</p>
            <div class="message-text">
              {{ item.text }}
            </div>
          </div>
        </div>
      </div>
      <el-input size="small" placeholder="说亿点好听的…" v-model="message" maxlength="200" @keyup.enter.native="send">
        <template slot="append">
          <el-button @click="send">发送</el-button>
        </template>
      </el-input>
    </div>
  </el-card>
</template>

<script>
import {getToken} from "@/utils/auth";
import dayjs from "dayjs";

export default {
  name: "Chatroom",
  data() {
    return {
      socket: null,
      message: '',
      dataList: [],
    }
  },
  created() {
    this.join()
  },
  methods: {
    join() {
      this.socket = new WebSocket(`wss://${location.host}${process.env.VUE_APP_BASE_API}/websocket/message?Authorization=Bearer ${getToken()}`);
      this.socket.addEventListener('open', () => {
        console.log('连接成功')
      })
      this.socket.addEventListener('message', (event) => {
        try {
          const msg = JSON.parse(event.data)
          this.dataList.push(msg)
          this.$nextTick(() => {
            this.$refs.container.scrollTop = this.$refs.container.scrollHeight;
          });
        } catch (err) {
          console.log('接收消息：' + event.data)
        }
      });
      this.socket.addEventListener('close', () => {
        this.socket = null;
        this.dataList.push({
          avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/160/h/160',
          info: '系统消息 【' + dayjs().format('HH:mm:ss') + '】',
          text: '连接关闭，请重新连接',
          type: 'left',
        })
      });
    },
    again() {
      if (!this.socket) {
        this.join()
      }
    },
    exit() {
      if (this.socket) {
        this.socket.close();
        this.socket = null;
      }
    },
    send() {
      if (!this.socket) {
        this.$message.error('未连接到服务器')
      }
      if (this.message.trim()) {
        this.socket.send(this.message);
        this.message = ''
      }
    },
  }
}
</script>
<style scoped lang="scss">
.container {
  height: calc(100% - 32px);
  overflow: auto;
  // 平滑滚动
  scroll-behavior: smooth;
}

.message-avatar {
  height: 38px;
  width: 38px;
  border-radius: 50%;
  margin: 0 10px;
}

.message {
  display: flex;
  margin-bottom: 20px;
  position: relative;
}

.message.right {
  flex-direction: row-reverse;
}

.message-text {
  display: inline-block;
  background-color: #e9e9eb;
  border-radius: 8px;
  padding: 8px 12px;
  line-height: 1.4;
  word-break: break-word;
  font-size: 14px;
}

.message.right .message-text {
  background-color: #409eff;
  color: white;
  float: right;
}

.message-info {
  color: #999;
  font-size: 12px;
  margin-top: 0;
  margin-bottom: 5px;
}

.message.right .message-info {
  text-align: right;
}
</style>
